package com.dhp.campus.schedule;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dhp.campus.domain.User;
import com.dhp.campus.mapper.UserMapper;
import com.dhp.campus.utils.RedisUtil;
import com.google.gson.Gson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

import static com.dhp.campus.Constant.LockConstant.CACHE_LOCK_KEY;
import static com.dhp.campus.Constant.UserConstant.RECOMMEND_USERS;


@Component
public class Precache {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private RedissonClient redissonClient;


    /**
     * 缓存预热
     */
    @Scheduled(cron = "0 24 22 * * *")
    public void PreStoreData(){
        Gson gson = new Gson();
        //1. 查询数据库中的数据（分页查询）
        Page<User> page = userMapper.selectPage(new Page<User>(1, 20), null);
            //2. 将其存入redis'
        RLock lock = redissonClient.getLock(CACHE_LOCK_KEY);
        try {
            if (lock.tryLock(0 , -1 , TimeUnit.MILLISECONDS)) {
                try {
                    String jsonStr = gson.toJson(page.getRecords());
                    redisUtil.set(RECOMMEND_USERS + 1L, jsonStr, 1, TimeUnit.DAYS);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            if (lock.isHeldByCurrentThread()){
                lock.unlock();
            }
        }

    }


}
